package com.pubsys.main.client.paginas.login.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.pubsys.main.client.componentes.botao.ButtonClickEvent;
import com.pubsys.main.client.componentes.botao.ButtonWidget;
import com.pubsys.main.client.rpc.login.LoginService;
import com.pubsys.main.client.rpc.login.LoginServiceAsync;
import com.pubsys.main.shared.model.Autor;
import com.google.gwt.user.client.ui.Grid;

public class LoginUI extends Composite {
	private static LoginServiceAsync loginService = GWT.create(LoginService.class);
	private static LoginUIUiBinder uiBinder = GWT.create(LoginUIUiBinder.class);
	@UiField TextBox userTextBox;
	@UiField PasswordTextBox passwordTextBox;
	@UiField ButtonWidget buttonWidget;
	@UiField Label statusLab;
	@UiField ButtonWidget logoutBtn;
	@UiField Grid loginBox;

	interface LoginUIUiBinder extends UiBinder<Widget, LoginUI> {
	}

	public LoginUI() {
		initWidget(uiBinder.createAndBindUi(this));
		
	    loginService.pegaUsuarioLogado(new AsyncCallback<Autor>() {			
			@Override
			public void onSuccess(Autor result) {
				boolean logado = (result != null && result.getEmail() != null && !result.getEmail().trim().equals(""));
				logoutBtn.setVisible(logado);
				loginBox.setVisible(!logado);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}
		});
	}

	@UiHandler("buttonWidget")
	void onButtonWidgetClick(ButtonClickEvent event) {
		String login, senha;
		login = userTextBox.getText();
		senha = passwordTextBox.getText();
		
		if (login.trim().equals("") && senha.trim().equals("")){
			statusLab.setText("Favor completar campos com usuario e senha");
			return;
		}
			
		LoginServiceAsync service = GWT.create(LoginService.class);
		service.login(login, senha, new AsyncCallback<Void>() {			
			@Override
			public void onSuccess(Void result) {
				Location.reload();
			}
			
			@Override
			public void onFailure(Throwable caught) {
				statusLab.setText(caught.getMessage());
			}
		});
		
		
	}
	@UiHandler("logoutBtn")
	void onLogoutBtnClick(ButtonClickEvent event) {
		loginService.logout(new AsyncCallback<Void>() {			
			@Override
			public void onSuccess(Void result) {
				Location.reload();
			}
			
			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}
}
